﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EditPcName
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0) {
                Console.WriteLine("请至少输入一个值");
                return;
            }
            SetComputerName(args[0]);
        }
        private static void SetComputerName(string computerName)
        {
            try
            {
                String curName = System.Net.Dns.GetHostName();
                if (curName.Equals(computerName)) {
                    Console.WriteLine("计算机名称已修改，无需重复修改");
                    return;
                }

                RegistryKey pregkey;
                pregkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\ControlSet001\\Control\\ComputerName\\ComputerName", true);
                pregkey.SetValue("ComputerName", computerName);
                pregkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters", true);
                pregkey.SetValue("NV Hostname", computerName);
                pregkey.SetValue("Hostname", computerName);
                pregkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName", true);
                pregkey.SetValue("ComputerName", computerName);
                pregkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", true);
                pregkey.SetValue("NV Hostname", computerName);
                pregkey.SetValue("Hostname", computerName);
                Console.WriteLine("修改计算机名称成功");
                Console.WriteLine(String.Format("修改后计算机名称为:{0}", System.Net.Dns.GetHostName()));
                //textBox1.Text = System.Net.Dns.GetHostName();
                //textBox2.Text = "";

            }
            catch (Exception)
            {
                Console.WriteLine("修改失败，没访问注册表权限请用管理员身份运行！");
                throw;
            }


        }
    }
}
